import React, {useEffect, useRef, useState, Fragment} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table';
import {TableListItem} from './data.d';
import {queryPageList, updateUser, addUser, removeUser, userDetail} from "@/pages/Setting/SysUser/service";
import {queryPageRoleList} from "@/pages/Setting/SysRole/service";
import moment from 'moment';
import {Divider, Button, message, Select, Tooltip, TreeSelect} from "antd";
import CreateForm from "./components/CreateForm";
import UpdateForm from "./components/UpdateForm";
import {DeleteOutlined, FormOutlined, PlusOutlined} from "@ant-design/icons/lib";
import {queryPageGroupList} from "@/pages/Setting/SysGroup/service";
import {formPropsLayout} from "@/utils/tableUtils";


const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在更新');
  const res = await updateUser(fields);
  hide();
  if (res.code == 10000) {
    message.success('更新成功');
    return true;
  }
  message.error('更新失败，请重试');
  return false
};


const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  const res = await addUser(fields);
  hide();
  if (res.code == 10000) {
    message.success('添加成功');
    return true;
  }
  message.error('更新失败，请重试');
  return false;
};

const handleRemove = async (id: number) => {
  const hide = message.loading('正在删除');

  const res = await removeUser({id: id});
  hide();
  if (res.code == 10000) {
    message.success('删除成功，即将刷新');
    return true;
  }
  message.error('删除失败，请重试');
  return false;

};

const init = {id: 0};


const SysUser: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState<TableListItem>(init);
  const [role, setRole] = useState([])
  const [groupList, setGroupList] = useState([])

  useEffect(() => {
    queryPageRoleList({currPage: 1, pageSize: 100000}).then(res => {
      setRole(res.data.rows);
    });
    queryPageGroupList().then(res => {
      setGroupList(res.data);
    });
  }, [])


  const columns: ProColumns<TableListItem>[] = [
    {
      title: '账号',
      dataIndex: 'username',
      hideInSearch: true,
      initialValue: stepFormValues.username,
      formItemProps: {
        rules: [
          {
            message: "账号为必填项！",
            required: true
          }
        ]
      }
    },
    {
      title: '名称',
      dataIndex: 'nickname',
      initialValue: stepFormValues.nickname,
      formItemProps: {
        rules: [
          {
            message: "名称为必填项！",
            required: true
          }
        ]
      }
    },
    {
      title: '手机',
      dataIndex: 'phone',
      initialValue: stepFormValues.phone,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            message: "手机为必填项！",
            required: true
          }
        ]
      }
    },
    {
      title: '密码',
      dataIndex: 'password',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: stepFormValues.id == 0,
            message: '密码为必填项',
          },
        ]
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      initialValue: stepFormValues.status,
      valueEnum: {
        "enable": {text: '启用', status: 'Success'},
        "disable": {text: '禁用', status: 'Error'},
      },
      formItemProps: {
        rules: [
          {
            message: "状态为必选项！",
            required: true
          }
        ]
      }
    },
    {
      title: '角色',
      dataIndex: 'roles',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: stepFormValues.username == "admin",
      initialValue: stepFormValues.roles,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        return <Select placeholder="请选择角色" mode="multiple" style={{width: '100%'}}>
          {role.map((v: any) => {
            return (
              <Select.Option key={v.id} value={v.id}>
                {v.name}
              </Select.Option>
            );
          })}
        </Select>;
      }
    },
    {
      title: '用户组',
      dataIndex: 'groups',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: stepFormValues.username == "admin",
      initialValue: stepFormValues.groups,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        return <TreeSelect showCheckedStrategy={TreeSelect.SHOW_ALL} placeholder="请选择用户组" treeData={groupList}
                           fieldNames={{label: 'name', value: 'id', children: 'children'}}
                           style={{width: '100%'}} multiple />
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      hideInForm: true,
      render: (val: any) => moment(val).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      hideInSearch: true,
      hideInForm: true,
      render: (val: any) => moment(val).format('YYYY-MM-DD HH:mm')
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      hideInForm: true,
      render: (text, record) => (
        <Fragment>
          <span>
            <a
              onClick={() => {
                userDetail({id: record.id}).then(res => {
                  if (res.code === 10000) {
                    setStepFormValues(res.data || {});
                    handleUpdateModalVisible(true);
                  }
                })
              }}
            >
              <Tooltip title="编辑">
             <FormOutlined/>
              </Tooltip>
            </a>
            <Divider type="vertical"/>
          </span>
          {"admin" !== record.username &&
          <a onClick={async () => {
            let promise = await handleRemove(record.id);
            if (promise && actionRef.current) actionRef.current.reload()
          }}>
            <Tooltip title="删除">
              <DeleteOutlined/>
            </Tooltip>
          </a>
          }
        </Fragment>
      ),
    },
  ];


  return (
    <PageContainer>
      <ProTable<TableListItem>
        headerTitle="用户列表"
        actionRef={actionRef}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        rowKey="id"
        request={(params) => queryPageList({...params, currPage: params.current}).then(res => {
          const result = {data: [], total: 0, success: false};

          if (res.code === 10000) {
            result.data = res.data.rows ?? [];
            result.total = res.data.totalCount;
            result.success = true;
          }
          return result
        })}
        columns={columns}
      />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable<TableListItem, TableListItem>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={formPropsLayout}
          rowKey="id"
          type="form"
          columns={columns}
          rowSelection={{}}
        />
      </CreateForm>
      {stepFormValues && Object.keys(stepFormValues).length && (
        <UpdateForm
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues(init);
          }}
          updateModalVisible={updateModalVisible}
        >
          <ProTable<TableListItem, TableListItem>
            onSubmit={async (value) => {
              value.id = stepFormValues.id;
              const success = await handleUpdate(value);
              if (success) {
                handleUpdateModalVisible(false);
                setStepFormValues(init);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            form={formPropsLayout}
            rowKey="key"
            type="form"
            columns={columns}
            rowSelection={{}}
          />
        </UpdateForm>
      )}
    </PageContainer>
  );
};

export default SysUser;
